package com.minidb.sql_compiler;

import com.minidb.engine.PlanNode;

public class Planner {
    public PlanNode createPlan(SQLStatement s) {
        switch (s.type) {
            case SELECT -> {
                PlanNode scan = new PlanNode("SeqScan");
                scan.props.put("table", s.tableName);
                if (s.condition != null) {
                    PlanNode filter = new PlanNode("Filter");
                    filter.props.put("condition", s.condition.toString());
                    filter.addChild(scan);
                    PlanNode project = new PlanNode("Project");
                    project.props.put("columns", s.columns==null||s.columns.isEmpty()?"*":String.join(",",s.columns));
                    project.addChild(filter);
                    return project;
                } else {
                    PlanNode project = new PlanNode("Project");
                    project.props.put("columns", s.columns==null||s.columns.isEmpty()?"*":String.join(",",s.columns));
                    project.addChild(scan);
                    return project;
                }
            }
            case INSERT -> {
                PlanNode ins = new PlanNode("Insert");
                ins.props.put("table", s.tableName);
                ins.props.put("values", String.join(",", s.values));
                return ins;
            }
            case CREATE_TABLE -> {
                PlanNode ct = new PlanNode("CreateTable");
                ct.props.put("table", s.tableName);
                ct.props.put("columns", String.join(",", s.columns));
                ct.props.put("types", String.join(",", s.columnTypes));
                return ct;
            }
            case DELETE -> {
                PlanNode scan = new PlanNode("SeqScan");
                scan.props.put("table", s.tableName);
                if (s.condition != null) {
                    PlanNode delete = new PlanNode("Delete");
                    delete.props.put("condition", s.condition.toString());
                    delete.addChild(scan);
                    return delete;
                } else {
                    PlanNode delete = new PlanNode("Delete");
                    delete.props.put("condition", "ALL");
                    delete.addChild(scan);
                    return delete;
                }
            }
            default -> { return new PlanNode("Unknown"); }
        }
    }
}
